<template>
  <div class="database-user-container">
    <div v-show="$route.meta.isShows" class="app-container">
      <!-- 头部 -->
      <div class="filter-container flex-r justify-sb align-item-ct">
        <div class="flex-r align-item-ct justify-ct">
          <el-input
            v-model="newSearch"
            placeholder="请输入QID、姓名、身份证号码、住院号进行搜索"
            style="width: 200px"
            clearable
            @change="newInquire"
            @clear="newclear"
          />
          <el-button
            v-waves
            class="margin-l20"
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="newInquire"
          >
            查询
          </el-button>
        </div>
        <!-- 没有选中 -->
        <div
          v-if="!isUser.statue"
          class="flex-r align-item-ct justify-ct"
        >

          <el-tooltip
            content="暂无新增权限"
            placement="top"
            effect="light"
            :disabled="getAuth('2')"
          >
            <div>
              <el-button
                class="margin-r40"
                style="margin-left: 10px"
                size="mini"
                type="primary"
                icon="el-icon-plus"
                :disabled="!getAuth('2')"
                round
                @click="dialogFormVisible=true"
              >
                新增患者
              </el-button>
            </div>
          </el-tooltip>
          <el-tooltip
            content="暂无复制权限"
            placement="top"
            effect="light"
            :disabled="getAuth('5')"
          >
            <div>
              <el-button
                class="tools"
                :disabled="!getAuth('5')"
                @click.native.prevent="copyUser('1')"
              >一键复制</el-button>
            </div>
          </el-tooltip>
        </div>
        <!-- 选中状态 -->
        <div v-else class="flex-r align-item-ct justify-ct">
          <el-button
            class="tools margin-l10"
          >已选择{{ isUser.count }}</el-button>
          <el-tooltip
            content="暂无导出权限"
            placement="top"
            effect="light"
            :disabled="getAuth('6')"
          >
            <div>
              <el-button
                class="tools"
                :disabled="!getAuth('6')"
                @click.native.prevent="outputCase"
              >导出病例</el-button>
            </div>
          </el-tooltip>
          <el-tooltip
            content="暂无复制权限"
            placement="top"
            effect="light"
            :disabled="getAuth('5')"
          >
            <div>
              <el-button
                class="tools"
                :disabled="!getAuth('5')"
                @click="copyUser('2')"
              >复制病例</el-button>
            </div>
          </el-tooltip>
          <el-tooltip
            content="暂无删除权限"
            placement="top"
            effect="light"
            :disabled="getAuth('4')"
          >
            <div>
              <el-button
                class="tools"
                icon="el-icon-delete"
                :disabled="!getAuth('4')"
                @click.native.prevent="newdelete"
              >删除</el-button>
            </div>
          </el-tooltip>
          <el-divider direction="vertical" />
          <el-button
            class="tools"
            @click.native.prevent="cancelSelect"
          >取消</el-button>
        </div>
      </div>
      <!-- 数据库详情展示 -->
      <div class="Database">
        <userTable ref="userTable" :new-search="newSearch" :information="information" :total-number="totalNumber" @cancelSelect="cancelSelect" @sendUser="receiveUser" @sendIsUser="receiveIsUser" @Delete_users="Delete_users" />
      </div>
      <!-- 新增患者弹框 -->
      <el-dialog
        append-to-body
        center
        title="新增病历用户"
        :visible.sync="dialogFormVisible"
        width="40%"
        @close="closeAddUser"
      >
        <el-form
          ref="dataForm"
          :model="addUserInfo"
          :rules="rules"
          label-position="left"
          style="width: 400px; margin-left: 50px"
        >
          <el-form-item prop="user_name">
            <div style="display:flex">
              <span style="width:25%;">姓名<span style="color:red;">*</span></span>
              <el-input v-model="addUserInfo.user_name" />
            </div>
          </el-form-item>
          <el-form-item prop="id_card_no">
            <div style="display:flex">
              <span style="width:25%;">身份证号</span>
              <el-input
                v-model="addUserInfo.id_card_no"
                type="text"
                minlength="15"
                maxlength="18"
                onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"
              />
            </div>
          </el-form-item>
          <el-form-item prop="user_sex">
            <div style="display:flex;align-items:center">
              <span style="width:20%;">性别</span>
              <el-radio-group v-model="addUserInfo.user_sex" style="width:75%">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <el-form-item prop="user_birthday">
            <div style="display:flex">
              <span style="width:20%;">出生日期</span>
              <el-date-picker
                v-model="addUserInfo.user_birthday"
                prefix-icon="el-icon-time"
                type="date"
                placeholder="请输入出生日期"
                value-format="yyyy-MM-dd"
              />
            </div>

          </el-form-item>
          <!-- onkeyup="value=value.replace(/[^0-9]/ig,'')<1?'':value.replace(/[^0-9]/ig,'')>150?'':value.replace(/[^0-9]/ig,'')" -->
          <el-form-item>
            <div style="display:flex;align-items:center">
              <span style="width:25%;">年龄</span>
              <el-input
                :value="addUserInfo.user_age"
                placeholder="请输入年龄（1-150）"
                @input="changeinput_age($event,'年龄')"
              />
            </div>
          </el-form-item>
          <el-form-item prop="hospital_number">
            <div style="display:flex;align-items:center">
              <span style="width:25%;">住院号</span>
              <el-input v-model="addUserInfo.hospital_number" />
            </div>
          </el-form-item>
          <p>无住院号时填写诊疗卡</p>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false"> 取消 </el-button>
          <el-button type="primary" @click="establish"> 创建 </el-button>
        </div>
      </el-dialog>
      <!-- 复制弹框 -->
      <DatabaseChildSelect :new-child-db-info="newChildDbInfo" :is-select-database.sync="isSelectDatabase" :new-user="newUser" :new-differentiate="newDifferentiate" @sendIsSelectDatabase="receiveIsSelectDatabase" />

    </div>
    <router-view />
  </div>
</template>

<script>
import userTable from '@/components/UserTable'
import DatabaseChildSelect from '@/components/DatabaseChildSelect'
// 封装病人列表信息 创建病例 删除病例
import { getUserList, addCaseUser, deleteUser } from '@/api/case'
export default {
  components: {
    userTable,
    DatabaseChildSelect
  },
  data() {
    // 表单验证函数
    var validateName = (rule, value, callback) => {
      value = this.addUserInfo.user_name
      this.addUserInfo.user_name = value
        .replace(/[^\u4e00-\u9fa5a-zA-Z0-9\w]/g, '')
        .trim()
      if (value === '') {
        callback(new Error('请填写姓名'))
        return
      } else {
        callback()
      }
    }
    var validateCard = (rule, value, callback) => {
      console.log('fdfgflkgklgfn')
      value = this.addUserInfo.id_card_no
      const myDate = new Date()
      this.addUserInfo.id_card_no = value
        .replace(/[^\u4e00-\u9fa5a-zA-Z0-9\w]/g, '')
        .trim()
      const id_card_no = this.addUserInfo.id_card_no
      // 获取性别，年龄，出生日期
      if (id_card_no.length === 18) {
        const age = myDate.getFullYear() - id_card_no.substring(6, 10)
        const sex = id_card_no.substring(16, 17)
        const birth = id_card_no.substring(6, 10) + '-' + id_card_no.substring(10, 12) + '-' + id_card_no.substring(12, 14)
        this.addUserInfo.user_sex = sex % 2 === 0 ? 2 : 1
        this.addUserInfo.user_age = age
        this.addUserInfo.user_birthday = birth
      }
      callback()
    }
    return {
      database_id: '', // 数据库id
      template_id: '', // 模板id
      isUser: { statue: false, count: 0 }, // 选中病人信息
      information: this.$store.state.database.information.list, // 病人信息渲染部分
      totalNumber: this.$store.state.database.information.total, // 总条数
      newSearch: '', // 搜索
      newPage: '1', // 这里就是页数
      newPage_sum: '10', // 这里就是默认条数
      newOrder_sort: 'DESC', // 这里就是排序
      dialogFormVisible: false, // 新增患者弹框控制
      isSelectDatabase: false, // 复制弹框
      addUserInfo: {
        // 新增病例 总库/子库新增
        user_name: '', // 用户姓名
        id_card_no: '', // 身份证号
        user_sex: '', // 性别
        user_birthday: '', // 出生日期
        user_age: '', // 年龄
        hospital_number: '' // 住院号
      },
      // 新增病人表单验证
      rules: {
        user_name: [
          { required: true, validator: validateName, trigger: 'blur' }
        ],
        id_card_no: [
          { validator: validateCard, trigger: 'blur' }
        ]
      },
      newDelete_users: [], // 这里就是用户选中的id
      newUser: [], // 选中用户的全部内容
      newChildDbInfo: [], // 这里就是选择数据库展示的内容
      newDifferentiate: true // 区分用户选中的是一键复制还是单个 true 就是一键复制 反之不是

    }
  },
  computed: {
    // 判断用户是否有权限
    getAuth(index) {
      return index => {
        const auth = this.$store.state.database.information.auths.auth
        const res = auth.indexOf(index)
        if (res === -1) {
          return false
        } else {
          return true
        }
      }
    }
  },
  created() {
    console.log('$route.meta.isShow$route.meta.isShow$route.meta.isShow', this.$route.meta)
    // 将数据库id赋值
    this.database_id = this.$store.getters.database_id
    // 赋值模板id
    this.template_id = this.$store.getters.template_id
    console.log('进来了的id', this.$store.getters.database_id)
    this.newGetUserList(this.$store.getters.database_id, this.newSearch, this.newPage, this.newPage_sum, this.newOrder_sort)
  },
  methods: {
    // 显示年龄的输入
    changeinput_age(e) {
      var reg = /^\d|([1-9]\d)|(1[0-4]\d)|(150)$/
      var num = e
      console.log(num.length)
      console.log(reg.test(num))
      console.log(num.length <= 3)
      console.log(this.addUserInfo.user_age)
      if (reg.test(num) && num.length <= 3 && num <= 150 && num > 0 || num === '') {
        this.addUserInfo.user_age = num
        this.$forceUpdate()
        console.log(e)
        console.log(this.addUserInfo.user_age)
      } else {
        return
      }
    },
    newclear() {
      console.log('清空数据')
      // 清空数据之后需要重新获取数据
      this.newGetUserList(this.$store.getters.database_id, this.newSearch, this.newPage, this.newPage_sum, this.newOrder_sort)
    },
    // 点击查询
    newInquire() {
      console.log('点击查询了', this.newSearch)
      // 初始选中状态
      this.isUser = { statue: false, count: 0 }
      // // 非空判断
      // if (!this.newSearch) {
      //   // 如果没有数据
      //   return this.$message.error('请输入搜索内容')
      // }
      // 请求接口
      this.newGetUserList(this.$store.getters.database_id, this.newSearch.trim(), this.newPage, this.newPage_sum, this.newOrder_sort)
    },
    // 点击确定删除所选用户
    async newConfirm() {
      // 调用接口
      const data = { database_id: this.database_id, delete_users: this.newDelete_users }
      const res = await deleteUser(data)
      console.log('删除提示', res)
      // 需要重新发送请求调用接口
      this.newGetUserList(this.$store.getters.database_id, this.newSearch, this.newPage, this.newPage_sum, this.newOrder_sort)
      // 初始选中状态
      this.isUser = { statue: false, count: 0 }
      this.$message.success('删除成功')
    },
    // 这里就是传过来的id
    Delete_users(e) {
      console.log('我是父组件', e)
      this.newUser = e
      const res = e.map((e) => {
        return e.id
      })

      this.newDelete_users = res
      console.log('ressssss', this.newDelete_users)
    },
    // 点击删除
    newdelete() {
      // 先校验是否删除
      this.$confirm('确定移除所选用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(
        () => {
          this.newConfirm()
          this.cancelSelect()
        }
      ).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 创建病例 establish
    async establish() {
      // 先校验
      try { await this.$refs.dataForm.validate() } catch (e) {
        return
      }
      if (this.addUserInfo.id_card_no.length === 0) {
        console.log('是0位直接过')
      } else {
        if (this.addUserInfo.id_card_no.length !== 18) {
          return this.$message.error('请输入正确的身份证信息')
        }
      }
      console.log('点击创建病例', this.addUserInfo, this.$store.getters.database_id, this.$store.getters.template_id)
      // 分析 因为这里是总库 所以master_db_id他的id和总库database_id一样 把数据组合起来
      // 因为是总库所以使用赋值的
      const master_db_id = this.$store.state.user.getSelect.id
      this.addUserInfo.database_id = this.database_id
      this.addUserInfo.template_id = this.template_id
      this.addUserInfo.master_db_id = master_db_id
      this.addUserInfo.user_age = Math.floor(this.addUserInfo.user_age)
      // user_age === 0，后台需要空字符串
      if (this.addUserInfo.user_age === 0) {
        this.addUserInfo.user_age = ''
      }
      // 调用接口
      console.log(' this.addUserInfo', this.addUserInfo)
      const res = await addCaseUser(this.addUserInfo)
      if (res.data.code === 1) {
        this.$message.success(res.data.msg)
      } else {
        this.$message.error(res.data.msg)
      }
      // console.log('ressssssssss', res.)
      // 给出提示

      // 关闭弹窗
      this.dialogFormVisible = false
      this.newGetUserList(this.$store.state.database.database_id, this.newSearch, this.newPage, this.newPage_sum, this.newOrder_sort)
    },
    // 接收选中病人信息
    receiveIsUser(isUser) {
      this.isUser = isUser
    },
    // 接收病人信息
    receiveUser(obj) {
      this.information = obj.information
      this.totalNumber = obj.totalNumber
    },
    // 封装病人列表信息
    async  newGetUserList(database_id, search, page, page_sum, order_sort) {
      const res = {
        database_id,
        search,
        page,
        page_sum,
        order_sort
      }
      const list = await getUserList(res)
      console.log('listttttttttttt', list)
      // 赋值
      this.information = list.data.data.list
      this.totalNumber = list.data.data.total // 数量
      this.$store.dispatch('database/setInformation', list.data.data) //  将内容存到vuex中
      // this.$store.dispatch('database/setInformation', res.list)
    },
    // 复制病例
    copyUser(e) {
      if (e === '1') {
        this.newDifferentiate = true
        // 如果等于1说明就是一键复制
        console.log('一键复制')
      } else {
        console.log('不是一键复制')
        this.newDifferentiate = false
      }
      this.isSelectDatabase = true
      // 点击复制病例需要拿到子库
      // console.log(' 点击复制病例需要拿到子库', this.$store.state.user.getSelect.childDbInfo)
      // 判断是否有子库
      if (this.$store.state.user.getSelect.childDbInfo) {
        // 如果有将数据赋值
        this.newChildDbInfo = this.$store.state.user.getSelect.childDbInfo
      }
    },
    // 接收复制弹框子组件的信息
    receiveIsSelectDatabase(isSelectDatabase) {
      this.isSelectDatabase = isSelectDatabase
    },
    // 获取域名
    getRealmName() {
      let host = ''
      if (process.env.NODE_ENV === 'development') {
        host = 'http://' + window.location.host + '/api'
      } else {
        host = 'http://' + window.location.host
      }
      return host
    },
    // 导出病例
    async outputCase() {
      const res = 1
      console.log('start')
      if (res) {
        console.log('end')
        // console.log(this.newDelete_users.join(','))
        // // 1charset=UTF-8
        // console.log('文件流', res.data)
        // const fileName = res.headers['content-disposition'].split(';')[1].split('filename=')[1]
        // // res.data = res.data.replace(reg, '')
        // console.log('文件名', fileName)
        // const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.ms-excel;charset=GB13080' })) // 处理文档流
        const user_ids = this.newDelete_users.join(',')
        // '37,36,35,34,32,31,30,28,8,7 '
        this.newDelete_users.join(',')
        const url = this.getRealmName() + '/db/DbUser/exportUsers?database_id=' + this.database_id + '&template_id=' + this.template_id + '&user_ids=' + user_ids + '&search=' + this.newSearch
        console.log('url', url)
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        document.body.appendChild(link)
        link.click()
      } else {
        this.$message.error('暂无数据，无法导出！')
      }
    },
    // 取消选择
    cancelSelect() {
      // 初始选中状态
      this.isUser = { statue: false, count: 0 }
      // 调用子组件的方法
      this.$refs.userTable.cancelSelect()
    },
    // 关闭患者弹框
    closeAddUser() {
      // 重置表单数据
      this.$refs.dataForm.clearValidate()
      this.addUserInfo = {
        // 新增病例 总库/子库新增
        user_name: '', // 用户姓名
        id_card_no: '', // 身份证号
        user_sex: '', // 性别
        user_birthday: '', // 出生日期
        user_age: '', // 年龄
        hospital_number: '' // 住院号
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.database-user-container{
  background: #f7f7f7;
  height: 100%;
}
.details{
  display: flex;
  flex-direction: column;
  margin-left: 10%;
  .header{
    display: flex;
  }
.Database{
  margin-top: 1%;
  width: 90%;
}
}
// ====
 .app-container {
    max-width: 1250px;
    min-width: 948px;
    // width: 1250px;
    margin: 12px auto 0;
    padding: 20px  ;
  }
.tools {
    background: #f7f7f7;
    border: none;
  }
.el-dialog__header:after {
    position: absolute !important;
    content: "" !important;
    width: calc(100% - 40px) !important;
    top: 53px;
    /* bottom: 0 !important; */
    left: 20px !important;
}
.positionT0L0{
  border-top: 1px solid #ddd;
width:100%;
min-height:100%;
padding:24px;
// padding-bottom:60px;
background-color:#f7f7f7;
position:absolute;
top:0;
left:0;
z-index:99;
}
</style>
